<?php
namespace Apps\Manage\Controllers;

use Apps\Common\Models\BeautyParlorInteractive;
use Phalcon\Http\Response;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Models\BeautyParlor;
use Apps\Common\Models\UserBase;
use Apps\Common\Models\Branch;
use Apps\Common\Libs\SmaUtil;
use Phalcon\Mvc\Model;
use Apps\Common\Libs\UploadPic;
/**
 * 美粒互动管理
 * @author     chenxiaolin
 * @date        2016年4月13日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class BpinteractController extends BpBaseController{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('bp');
    }
    /**
     * 美粒互动列表
     * @date: 2016年4月13日 
     * @author: chenxiaolin
     */
    public function listAction(){
        $this->setLeftNav('interact_list');
        $req = $this->request;
        
        $page = intval ( $req->getQuery ( 'page', null, 1 ) );
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);
        
        $id = intval($req->getQuery('id', null, 0));
        $content = $req->getQuery('content',null,'');
        //$state = intval($req->getQuery('state',null,-10000));
        $addtime = $req->getQuery('addtime');
        $timeSlotarr=explode("至",$addtime);
        if($id <= 0) {
            $this->view->disable();
            echo '美容院不存在！';
            return;
        }
        if($content!=''){
        	$where[] = "content like '%".$content."%'";
        	$this->view->setVar('content',$content);
        }
        /* if(!in_array($state,[-10000,-1,1])){
        	$this->view->disable();
        	echo '参数错误！';
        	return;
        }
        if($state > -10000){
        	$where[] = "state = $state";
        } */
        if($addtime != ''){
            $where[]="addtime > '".$timeSlotarr[0]."'";
            $where[]="addtime < '".$timeSlotarr[1]."'";
        }
        $where[]="bp_id = $id";
        $where[]="state = 1";
        $whereStr = implode(" and ",$where);
        $list = BeautyParlorInteractive::query()
            ->columns([
                'Apps\Common\Models\BeautyParlorInteractive.id',
                'Apps\Common\Models\BeautyParlorInteractive.content',
                'Apps\Common\Models\BeautyParlorInteractive.pics',
                'Apps\Common\Models\BeautyParlorInteractive.state',
                'Apps\Common\Models\BeautyParlorInteractive.addtime',
                'ub.user_nickname',
            ])
            ->leftJoin('Apps\Common\Models\UserBase', 'ub.user_id = Apps\Common\Models\BeautyParlorInteractive.user_id', 'ub')
            ->where($whereStr)
            ->orderBy ( 'addtime DESC,id DESC' )->limit ( $limit, $offset )
            ->execute();
        // 总数
        $total = BeautyParlorInteractive::count ( [
            'conditions' => $whereStr,
        ] );
        $this->view->setVar('interactList', $list);
        $this->view->setVar ( 'total', $total );
        $this->view->setVar ( 'page', $page );
        $this->view->setVar ( 'limit', $limit );
        $this->view->setVar('id', $id);
        //$this->view->setVar('state',$state);
        $this->view->setVar('addtime',$addtime);
    }
    /**
     * 添加美粒互动
     * @date: 2016年4月13日 
     * @author: chenxiaolin
     */
    public function addAction(){
        $this->setLeftNav('interact_add');
        $req = $this->request;
        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;
        
        $id = intval($req->getQuery('id', null, 0));
        if(!$req->isPost()){
            $bp = BeautyParlor::findFirst("bp_id = " . $id);
            if($id <= 0 || empty($bp)) {
                $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '美容院不存在！');
    	       return $response;
            }
            //该美容院是否已发布过美粒互动
            $count = BeautyParlorInteractive::count("bp_id = $id");
            if($count > 0){//已发布过
                //美容院是否开通线上店铺,且是否有app登录账号
                if(!empty($bp->branch_id)){
                    $branch = Branch::findFirst("shop_id = $bp->branch_id");
                    if($branch->status == 200){//开通了线上店铺
                        //是否有App登录账号
                        $smaUtil = new SmaUtil();
                        $shop_id = $branch->shop_id;
                        $login_name = $smaUtil->getMobile($shop_id);
                        $boss_name = $login_name['boss_mobile'];
                        $loginInfo = UserBase::findFirst("user_account = '".$boss_name."'");
                        if(!empty($loginInfo)){//有账号
                            $this->view->setVar('user',$loginInfo);
                        }else{//没有账号
                            $interact = BeautyParlorInteractive::findFirst("bp_id = $id");
                            $user = UserBase::findFirst("user_id = $interact->user_id");
                            $this->view->setVar('user',$user);
                        }
                    }
                }else{//未开通
                    $interact = BeautyParlorInteractive::findFirst("bp_id = $id");
                    $user = UserBase::findFirst("user_id = $interact->user_id");
                    $this->view->setVar('user',$user);
                }
            }else{//未发布过
                //美容院是否开通线上店铺,且是否有app登录账号
                if(!empty($bp->branch_id)){
                    $branch = Branch::findFirst("shop_id = $bp->branch_id");
                    if($branch->status == 200){//开通了线上店铺
                        //是否有App登录账号
                        $smaUtil = new SmaUtil();
                        $shop_id = $branch->shop_id;
                        $login_name = $smaUtil->getMobile($shop_id);
                        $boss_name = $login_name['boss_mobile'];
                        $loginInfo = UserBase::findFirst("user_account = '".$boss_name."'");
                        if(!empty($loginInfo)){//有账号
                            $this->view->setVar('user',$loginInfo);
                        }else{//没有账号
                            $userList=UserBase::find("is_manage = 1");
                            $this->view->setVar('userlist',$userList);
                        }
                    }
                }else{//未开通
                    $userList=UserBase::find("is_manage = 1");
                    $this->view->setVar('userlist',$userList);
                }    
            }
            $this->view->setVar('id',$id);
            $this->view->pick("bpinteract/add");
            return;
        }
        //添加
        $id = intval($req->getPost("bp_id",null,0));
        $content = $req->getPost('content',null,'');
    	$user_id = $req->getPost('user_id',null,0);
    	
    	//判断空数据
    	if($id <=0 || empty($content) || $user_id <= 0) {
    	    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
    	    return $response;
    	}
    	$contentLenth = $this->utf8_strlen($content);
    	if ($contentLenth > 500) {
    	    $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '内容不超过500字！');
    	    return $response;
    	}
    	$interactModel = new BeautyParlorInteractive();
    	//保存图片
        if($_FILES['pics']['name'][0]!=''){
    		$uploadFile = new UploadPic();
        	$uploadFile->request = $req;
        	$pics = $uploadFile->beautyParlorInteractive();
        	$interactModel->pics=json_encode($pics);
    	}else{
    		$interactModel->pics=json_encode([]);
    	}
    	$interactModel->content = $content;
    	$interactModel->state = 1;
    	$interactModel->bp_id = $id;
    	$interactModel->user_id = $user_id;
    	$interactModel->addtime = date("Y-m-d H:i:s");
    	if(!$interactModel->save()){
    	    $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
    	}
    	$response->sendResult('ok');
    	return $response;
    }
    /**
     * 删除美粒互动
     * @date: 2016年4月13日 
     * @author: chenxiaolin
     */
    public function setStateAction(){
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $state = intval($req->getPost('state', null, -10000));
            if($state != -1 || $id < 0) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            $info = BeautyParlorInteractive::findFirst('id=' . $id);
            //修改
            if($info) {
                $info->update(['state' => $state]);
            }
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }
    
    /**
     * 搜索发布人
     * @date: 2016年4月21日 
     * @author: chenxiaolin
     */
    public function searchuserAction(){
        $req = $this->request;
        $userName = $req->getPost('search_user',null,'');
        $list = UserBase::query()->columns(['user_nickname','user_id'])->where("user_nickname like :user_name: and is_manage = 1")->bind(['user_name'=>'%'.$userName.'%'])->execute()->toArray();
        $arr = [
            'list'=>$list
        ];
        echo json_encode($arr);
    }
    /**
     * 正则获取字符串长度
     * @date: 2016年4月21日 
     * @author: chenxiaolin
     */
    private function utf8_strlen($string = null)
    {
        // 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
        // 返回单元个数
        return count($match[0]);
    }
}
